import { HTTP } from "../../../utils/http"
import api from '../../../utils/api.js'
import { countdownTimer } from "../../../utils/util"
import { config } from '../../../utils/config'
let http = new HTTP()

Page({
	data: {
		imgUrl: config.imgUrl,
		order_list: [],
		current_page: 1,
		last_page: 1,
		interval_handle: null,
		refund_dlg_show: false,
		try_refund_order_id: 0,
		try_refund_product_name: "",
	},

	onLoad() {
		this.data.order_list = [];
		this.current_page = 1;
		this.last_page = 1;
		this.getMyGroupListForPage(this.current_page);
		this.data.interval_handle = setInterval(this.intervalHandle, 1000)
	},

	onShow() {
	},

	goUserList(event) {
		let dataIndex = event.currentTarget.dataset.index;
		wx.setStorageSync('group_user_list', this.data.order_list[dataIndex].user_list);
		return wx.navigateTo({
			url: '/pages/group-buy/gb-user-list/index',
		});
	},

	getMyGroupListForPage(page) {
		let _that = this;
		http.request({
			url: api.groupOrderMyList,
			method: "get",
			data: { page },
			success: function (res) {
				let order_list = _that.data.order_list.concat(res.data.data);
				order_list.forEach(element => {
					element.group_info.time = countdownTimer(element.group_info.expired_at);
				});
				_that.setData({
					order_list,
					current_page: page,
					last_page: res.data.last_page
				});
			}
		})
	},

	intervalHandle() {
		this.data.order_list.forEach(element => {
			element.group_info.time = countdownTimer(element.group_info.expired_at);
		})
		this.setData({ order_list: this.data.order_list })
	},

	/**
	 * 页面上拉触底事件的处理函数
	 */
	onReachBottom: function () {
		if (this.data.current_page < this.data.last_page) {
			this.data.current_page += 1;
			this.getMyGroupListForPage(this.data.current_page);
		} else {
			console.log("已经到底了");
		}
	},

	refundDlgToggle() {
		this.setData({
			refund_dlg_show: !this.data.refund_dlg_show
		})
	},

	// 点击退团按钮
	tryRefundGroup(event) {
		let dataset = event.currentTarget.dataset;
		this.setData({
			try_refund_order_id: dataset.oid,
			try_refund_product_name: dataset.pname,
		});
		this.refundDlgToggle();
	},

	// 退出拼团
	doGroupRefund() {
		// 关闭弹窗
		this.setData({ refund_dlg_show: false });
		let order_id = this.data.try_refund_order_id;
		let _that = this;
		http.request({
			url: api.groupOrderRefund,
			method: "post",
			data: { order_id },
			success: function (res) {
				if (res.code == 200) {
					wx.showToast({
						title: '成功退出拼团！',
						icon: 'none'
					})
					// 刷新页面
					_that.onLoad();
				} else {
					wx.showToast({
						title: "退团失败-" + res.message,
						icon: 'none'
					})
				}
			}
		})
	}
})